import { useMemo } from "react"
//这个hook用于操作本地存储
import {useLocation} from "react-router-dom"
declare global {
    interface Window {
        [k:string] :any
    }
}


type methods = {
    set: (value: any) => void
    rm: () => void
}

type Istorage = (key:string,storageType?:string) =>[string | null,methods]

const useStorage:Istorage = (key,storageType = 'localStorage')=>{
    
    let Location = useLocation()
    //获取值处理逻辑 key
    let localValue = useMemo(()=>{
        let localRes
        try {
            localRes = window[storageType].getItem(key)
            localRes = localRes ? JSON.parse(localRes) : null
            return localRes
        } catch (e:any) {
            console.log('useStorage 获取token 报错',e.toString())
            return null
        }
    },[Location])

    //操作值逻辑
    let method:methods = {
        set:async (value)=>{
        let valueJson
        try {
                valueJson = JSON.stringify(value)
                await window[storageType].setItem(key,valueJson)
            } catch (e) {
                console.log('useStorage 存token 报错',e);
            }
        },
        rm:() => window[storageType].removeItem(key)
        
    }
    return [localValue,method]
    
}

export default useStorage